package prj.carmap.mobile.process;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.DialogView;
import prj.carmap.mobile.activity.SellerListActivity;
import prj.carmap.mobile.model.SellerInfo;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 商家分类列表处理
 *
 */
public class SellerByTypeProcess extends AsyncHttpResponseHandler {
	private static AsyncHttpClient client = new AsyncHttpClient();

	private String typeName;
	private Context context;
	private String typeId;

	public void getSellerTypes(String typeId, String typeName) {
		this.typeName = typeName;
		CarmapApplication.popView = new DialogView(context);
		CarmapApplication.popView.show();
		StringBuilder url = new StringBuilder(CarmapApplication.SERVER_URL + "/rest/seller/bytype/");
		url.append(typeId + "/");
		url.append(CarmapApplication.getInstance().getLocData().longitude + "/");
		url.append(CarmapApplication.getInstance().getLocData().latitude);
		url.append("/0");
		client.get(url.toString(), this);
		this.typeId = typeId;
	}


	/**
	 * Fired when a request returns successfully, override to handle in your own code
	 * @param content the body of the HTTP response from the server
	 * @throws JSONException
	 */
	public void onSuccess(String content) {
		try {
			JSONArray jsonAry = new JSONArray(content);
			ArrayList<SellerInfo> sellers = new ArrayList<SellerInfo>();
			for (int i = 0; i < jsonAry.length(); i++) {
				JSONObject json = jsonAry.getJSONObject(i);
				sellers.add(SellerInfo.fromJson(json));
			}
			Intent intent = new Intent(context, SellerListActivity.class);
			intent.putExtra("sellers", sellers);
			intent.putExtra("title", typeName);
			intent.putExtra("sellerTypeId", typeId);
			context.startActivity(intent);
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		CarmapApplication.popView.hide();
	}

	/**
	 * Fired when a request fails to complete, override to handle in your own code
	 * @param error the underlying cause of the failure
	 * @param content the response body, if any
	 */
	public void onFailure(Throwable error, String content) {
		CarmapApplication.popView.hide();
		makeToast(R.string.error_net_connect);

	}

	private void makeToast(String content) {
		Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
	}

	private void makeToast(int content) {
		Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
	}

	public void setContext(Context context) {
		this.context = context;
	}

}
